<?php
require_once dirname(__FILE__) . '/../lib/Forage.php';
require_once 'Console/Getopt.php';

$short = 'vi:h';
$long  = array('verbose', 'index=', 'help');

function showHelp()
{
  $help = <<<END_TEXT
NAME
  faceting - Show facet information

SYNOPSIS
  php faceting.php [options] [query]

DESCRIPTION
  The parser utility of the wikipedia package parses Wikipedia dump
  files and indexes them through Forage in a supported backend.

OPTIONS
  -v, --verbose
    Print verbose logging messages
  -i DSN, --index=DSN
    The DSN used to load a Forage object to index the documents with
  -l LIMIT, --limit=LIMIT
    Limit the result set to LIMIT number of documents
  -d DEPTH, --depth=DEPTH
    Number of times to filter down into the facets
  -h, --help
    Show this help

EXAMPLE
  php searcher.php --verbose --index='solr:127.0.0.1:8080' pasta

END_TEXT;
  echo $help;
}

$con  = new Console_Getopt();
$args = $con->readPHPArgv();
array_shift($args);
$options = $con->getopt2($args, $short, $long);
$verbose = false;
$dsn     = null;
$limit   = 3;
$depth   = 2;
$query   = '';

if ($options instanceof PEAR_Error) {
  echo "Pear Error: " . $options->getMessage() . "\n";
  die();
}

foreach ($options[0] as $option) {
  switch ($option[0]) {
  case '--verbose':
  case 'v':
    $verbose = true;
    break;
  case '--index':
  case 'i':
    $dsn = $option[1];
    break;
  case '--limit':
  case 'l':
    $limit = $option[1];
    break;
  case '--depth':
  case 'd':
    $depth = $option[1];
    break;
  case '--help':
  case 'h':
  default:
    showHelp();
    die();
    break;
  }
}

$query = implode(' ', $options[1]);

if (!$dsn) {
  echo "ERROR: No index DSN set\n";
  die();
}

function display($response, $limit)
{
  $out   = '';
  $out  .= "Total: " . $response->total . "\n";
  $categories = $response->getFacet('category');
  $i     = 0;
  foreach ($categories as $category) {
    if (!$category->filter) {
      if ($i++>$limit) break;
      $out .= $category->value . ' (' . $category->count . ")\n";
    }
  }
  $out .= "\n";
  return $out;
}

function showFilters($response)
{
  $filter_values = $response->getFacet('category')->filter_values;

  $out = '';
  if (count($filter_values)>1) {
    $out .= "'" . implode("', '", array_slice($filter_values, 0, -1)) . "' and ";
  }
  $out .= "'" . array_pop(array_slice($filter_values, -1)) . "'";
  return $out;
}

$forage = Forage::create($dsn);
$document = new ForageDocument();

echo "Querying for: " . $query . "\n";
$query  = $forage->getQuery($query);
$query->setFacetFields(array('category'));
$response = $forage->search($query);
echo display($response, $limit);

for ($i=0; $i<$depth; $i++) {
  $facet = $response->getFacet('category');
  $query->addFacetFilter('category', $facet->values[$i]->value);
  $response = $forage->search($query);
  
  echo "Filtering on " . showFilters($response) . "\n";
  echo display($response, $limit);
}
